package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.utils.DateConvertUtils;
import com.hunttown.mes.common.utils.JSONUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.TransportSmsSendLogManageService;
import com.hunttown.mes.manage.service.TransportSmsTemplateManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.TransportSmsSendLogDTO;
import com.hunttown.mes.rpc.domain.TransportSmsTemplateDTO;
import com.hunttown.mes.rpc.domain.enums.api.CustomerEnum;
import com.hunttown.mes.rpc.domain.enums.sms.SmsTypeEnum;
import com.hunttown.mes.rpc.domain.query.TransportSmsSendLogDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportSmsTemplateDTOQuery;
import com.hunttown.common.domain.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 短信发送日志
 * @author: wangjunfu
 * @date: 2019-09-18 11:37:21
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/logsms")
public class SmsSendLogController {

    private final static Logger logger = LoggerFactory.getLogger(SmsSendLogController.class);

    private final TransportSmsSendLogManageService smsSendLogService;
    private final TransportSmsTemplateManageService smsTemplateService;
    private final AnalysisManageManageService manageService;
    private ModelService modelService;

    @Autowired
    public SmsSendLogController(TransportSmsSendLogManageService smsSendLogService, TransportSmsTemplateManageService smsTemplateService, AnalysisManageManageService manageService, ModelService modelService) {
        this.smsSendLogService = smsSendLogService;
        this.smsTemplateService = smsTemplateService;
        this.manageService = manageService;
        this.modelService = modelService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = {"/index", "/index-wx"}, method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, TransportSmsSendLogDTOQuery dtoQuery) {

        // 日期（初始化 2天）
        if (StringUtils.isBlank(dtoQuery.getDaterange())) {
            dtoQuery.setDaterange(String.format("%s ~ %s", DateConvertUtils.getPastDate(1), DateConvertUtils.getPastDate(0)));
        }

        dtoQuery.setOrderBy("order by id desc");
        Page<TransportSmsSendLogDTO> dataPage = smsSendLogService.getForPage(dtoQuery);

        // 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (TransportSmsSendLogDTO item : dataPage.getItems()) {
                item.setUserTypeName(CustomerEnum.getEnumByKey(item.getUserType()));
                item.setSmsTypeName(SmsTypeEnum.getEnumByKey(item.getSmsType()));
                item.setSendPeopleCn(modelService.getManageName(item.getSendPeople()));
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        //日期
        if (StringUtils.isNotBlank(dtoQuery.getDaterange())) {
            String[] date = dtoQuery.getDaterange().split("~");
            if (date.length == 2) {
                model.addAttribute("startDate", date[0].trim());
                model.addAttribute("endDate", date[1].trim());
            }
        }

        return request.getRequestURI();
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return vm
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        TransportSmsSendLogDTO obj;

        if (id > 0) {
            obj = smsSendLogService.getById(id);
        } else {
            obj = new TransportSmsSendLogDTO();
            obj.setId(0);
            obj.setStatus(0);
            obj.setUserId(0);
            obj.setEffectMinute(10);
        }
        model.addAttribute("Obj", obj);

        model.addAttribute("customerList", CustomerEnum.getEnumList()); //用户类型
        model.addAttribute("smsTypeList", SmsTypeEnum.getEnumList());   //短信类型

        //短信内容
        TransportSmsTemplateDTOQuery query = new TransportSmsTemplateDTOQuery();
        query.setStopFlag(0);
        query.setPageSize(100);
        Page<TransportSmsTemplateDTO> dataPage = smsTemplateService.getForPage(query);
        for (TransportSmsTemplateDTO item : dataPage.getItems()) {
            item.setSmsTypeName(SmsTypeEnum.getEnumByKey(item.getSmsType()));
        }
        model.addAttribute("templatePage", dataPage);

        return "basic/logsms/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, TransportSmsSendLogDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setInfoType(1);
                objDTO.setSendPeople(curr_obj.getId());
                objDTO.setSendTime(new Date());
                objDTO.setSmsTopic("");
                objDTO.setChannelId(1);
                objDTO.setReturnResult("OK");

                if (objDTO.getSmsType() == 30) {
                    objDTO.setEntId(-1);
                }

                objDTO = smsSendLogService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = smsSendLogService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return json
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        TransportSmsSendLogDTO obj = new TransportSmsSendLogDTO();
        obj.setId(id);

        if (id > 0) {
            obj = smsSendLogService.getById(id);
        }
        smsSendLogService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion
}